package com.wichell.framework.rocketmq.example.pull;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.rocketmq.client.consumer.DefaultMQPullConsumer;
import org.apache.rocketmq.client.consumer.PullResult;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.common.message.MessageQueue;

public class PullConsumerCommon {

	private static final Map<MessageQueue, Long> OFFSETABLE = new HashMap<MessageQueue, Long>();

	public static void main(String[] args) throws MQClientException {

		DefaultMQPullConsumer consumer = new DefaultMQPullConsumer("pullConsumerCommon");

		consumer.setNamesrvAddr("10.138.61.59:9876;10.138.61.57:9876");

		consumer.start();

		Set<MessageQueue> mqs = consumer.fetchSubscribeMessageQueues("TopicPull");

		for (MessageQueue mq : mqs) {

			System.out.println("Consume from the queue: " + mq);

			SINGLE_MQ: while (true) {

				try {

					PullResult pullResult =

							consumer.pullBlockIfNotFound(mq, null, getMessageQueueOffset(mq), 32);

					System.out.println(pullResult);

					putMessageQueueOffset(mq, pullResult.getNextBeginOffset());

					switch (pullResult.getPullStatus()) {

					case FOUND:
						List<MessageExt> msgFoundList = pullResult.getMsgFoundList();
						for (MessageExt messageExt : msgFoundList) {
							System.out.println(
									"receive msg:" + messageExt + "消息内容：" + new String(messageExt.getBody(), "UTF-8"));
						}

						break;

					case NO_MATCHED_MSG:

						break;

					case NO_NEW_MSG:

						break SINGLE_MQ;

					case OFFSET_ILLEGAL:

						break;

					default:

						break;

					}

				}

				catch (Exception e) {

					e.printStackTrace();

				}

			}

		}

		consumer.shutdown();

	}

	private static void putMessageQueueOffset(MessageQueue mq, long offset) {

		OFFSETABLE.put(mq, offset);

	}

	private static long getMessageQueueOffset(MessageQueue mq) {

		Long offset = OFFSETABLE.get(mq);

		if (offset != null) {
			return offset;
		}

		return 0;

	}

}
